const { login } = require("../control/user")
const { set } =require("../db/redis")
const { SuccessModel, ErrorModel } = require("../model/resModel")

const handleUserRouter = (req, res) => {
  const method = req.method
  const url = req.url
  const path = url.split("?")[0]

  // 登录
  if (method === "POST" && path === "/api/user/login") {
    if (req.body) {
      const result = login(req.body.username, req.body.password)
      return result.then(userData => {
        if(userData) {
          req.session.username = userData.username
          set(req.sessionId, req.session)
          return new SuccessModel(userData, "登录成功")
        } else {
          return new ErrorModel("登录失败")
        }
      })
    }
  }

  // if (method === "GET" && path === "/api/user/login") {
  //   if (req.query) {
  //     const result = login(req.query.username, req.query.password)
  //     return result.then(userData => {
  //       if(userData) {
  //         req.session.username = userData.username
  //         set(req.sessionId, req.session)
  //         console.log(req.session)
  //         return new SuccessModel(userData, "登录成功")
  //       } else {
  //         return new ErrorModel("登录失败")
  //       }
  //     })
  //   }
  // }
}

module.exports = {
  handleUserRouter
}
